package postgres

import (
	"manager/model"
	"manager/model/entity"
)

var Setting = &setting{}

type setting struct{}

func (a *setting) Create(m *entity.Setting) (int64, error) {
	err := db.Create(m).Error
	return m.Id, err
}

func (a *setting) Find(in *model.SettingUpdateRequest) (*entity.Setting, error) {
	var err error
	e := &entity.Setting{}
	if in.Id > 0 {
		err = db.Model(&entity.Setting{}).First(&e, in.Id).Error
		return e, err
	}

	gDb := db.Model(&entity.Setting{})
	if in.EbikeId != nil && *in.EbikeId > 0 {
		gDb = gDb.Model(&entity.Setting{}).Where("ebike_id = ?", in.EbikeId)
	}

	if in.UserId != nil && *in.UserId > 0 {
		gDb = gDb.Where("user_id = ?", in.UserId)
	}

	err = gDb.First(&e).Error
	return e, err

}

func (a *setting) Update(id int64, dict map[string]interface{}) error {
	if v, ok := dict["ebike_id"]; ok {
		return db.Model(&entity.Setting{}).Where("ebike_id = ?", v).Updates(dict).Error
	}
	return db.Model(&entity.Setting{}).Where("id = ?", id).Updates(dict).Error
}

func (a *setting) Delete(id int64) error {
	return db.Delete(&entity.Setting{}, id).Error
}

func (a *setting) BikeList(bikeIds []int64) (int, []*entity.Setting, error) {
	var (
		q        = db.Model(&entity.Setting{})
		err      error
		total    int64
		settings []*entity.Setting
	)

	if len(bikeIds) > 0 {
		q = q.Where("ebike_id in ?", bikeIds)
	}

	if err = q.Count(&total).Error; err != nil {
		return 0, nil, err
	}
	if err = q.Order("created_at desc").Find(&settings).Error; err != nil {
		return 0, nil, err
	}
	return int(total), settings, nil
}

func (a *setting) List(in *model.SettingListRequest) (int, []*entity.Setting, error) {
	var (
		q        = db.Model(&entity.Setting{})
		err      error
		total    int64
		settings []*entity.Setting
	)

	if in.EbikeId >= 0 {
		q = q.Where("ebike_id = ?", in.EbikeId)
	}

	if err = q.Count(&total).Error; err != nil {
		return 0, nil, err
	}
	if err = q.Order("created_at desc").Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&settings).Error; err != nil {
		return 0, nil, err
	}
	return int(total), settings, nil
}
